<?php

namespace app\api\controller\circle;

use app\admin\model\circle\CircleList;
use app\admin\model\circle\Comment;
use app\admin\model\circle\Fen;
use app\admin\model\circle\Love;
use app\admin\model\circle\Type;
use app\admin\model\circle\CircleTypeExtend;
use app\admin\model\main\School;
use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Sms as Smslib;
use app\common\library\Upload;
use app\common\model\User;
use think\Cache;
use think\Config;
use think\Db;
use think\Hook;
use getID3;


/**
 * 手机短信接口
 */
class Circle extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

//    -------------------------------圈子  学校相关接口 -------------------------------------------

    /**
     * 学校列表
     * @param  [type] $uid       [description]
     * @param  [type] $page      [description]
     * @param  [type] $page_size [description]
     * @return [type]            [description]
     */
    public function getXiaolist()
    {
        $userid = $this->request->post("uid") ?? @$this->auth->getUser()['id'];
        $list = School::field("id,name,image")->order('id asc')->select();
        if ($list) {
            $total = School::count();
            if (!empty($list)) {
                foreach ($list as $key => $value) {
                    $list[$key]['circle_count'] = $this->_circle_count(['xiao_id' => $value['id']]);
                    $list[$key]['user_count'] = $this->_circle_user_count(['tid' => $value['id']]);
                    $list[$key]['has_add'] = $this->_circle_user_count(['uid' => $userid, 'tid' => $value['id']]);
                    $list[$key]['image'] = $this->get_img($value['image']);
                }
            }
            $data = array('data' => $list, 'total' => $total);
            $this->success(__('获取成功'), $data);
        } else {
            $this->success(__('未获取到数据'), []);
        }
    }

    /**
     * 获取当前学校信息
     * @param  [type] $uid       [description]
     * @param  [type] $school_id     [description]
     * @return [type]            [description]
     */
    public function SchoolInfo()
    {
        $userid = $this->request->post("uid") ?? @$this->auth->getUser()['id'];
        $school_id = $this->request->post("school_id");
        if (empty($userid) || empty($school_id)) {
            $this->error(__('参数异常'));
        }
        $info = School::where(['id' => $school_id])->field("id,name,image")->find();
        $info['circle_count'] = $this->_circle_count(['xiao_id' => $school_id]);
        $info['user_count'] = $this->_circle_user_count(['tid' => $school_id]);
        $info['has_add'] = $this->_circle_user_count(['uid' => $userid, 'tid' => $school_id]);
        $info['image'] = $this->get_img($info['image']);

        $info['school_bj_img'] =$this->get_img(Config::get('site.school_bj_img'));
        $info['school_intro'] =Config::get('site.school_intro');

        $this->success(__('获取成功'), $info);
    }



    //加入圈子
    public function add_circle_user($uid, $school_id)
    {
        if (empty($uid) || empty($school_id)) {
            $this->error(__('参数异常'));
        }
        $fen['tid'] = $school_id;
        $fen['uid'] = $uid;
        $has = Db::name('circle_user')->where($fen)->find();
        if ($has) {
            $this->success(__('已加入圈子'), $fen);
        } else {
            $fen['createtime'] = time();
            $res = Db::name('circle_user')->insert($fen);
            $this->success(__('加入圈子成功'), $fen);
        }
    }
//    -------------------------------圈子  学校相关接口 -end------------------------------------------


//    -------------------------------圈子  圈子相关接口 -------------------------------------------
    /**
     * 圈子类型列表
     * @param  [type] $type       [description]
     * @return [type]            [description]
     */
    public function getTypelist()
    {
        $type = $this->request->post("type");
        $list = Type::where('type',$type)->field("id,name,info,pic")->select();
        if ($list) {
            foreach ($list as $key => $value) {
                $list[$key]['pic'] = $this->get_img($value['pic']);
            }
            $this->success(__('获取成功'), $list);
        } else {
            $this->success(__('未获取到数据'), []);
        }
    }

    /**
     * 圈子列表
     * @param  [type] $school_id  [description]
     * @param  [type] $type       [description]
     * @param  [type] $cir_id     [description]
     * @param  [type] $uid       [description]
     * @param  [type] $page      [description]
     * @param  [type] $orderby   [description]
     * @return [type]            [description]
     */
    public function getCirclelist($school_id, $type, $cir_id, $uid, $page, $orderby)
    {
        if (empty($uid) || empty($type) || empty($school_id)) {
            $this->error(__('参数异常'));
        }
        $page = $page ? $page : 1;    //当前分页
        $page_size = $this->request->post("page_size") ?? 10;    //当前分页
        $where['xiao_id'] = $school_id;
        $where['status'] = 1; //获取已经审核通过的圈子数据
        if ($cir_id) {
            $where['cir_id'] = $cir_id;
        } else {
            $cirids = Type::where('type', $type)->column('id');
            $where['cir_id'] = ['in', $cirids];
        }
        if ($orderby == "newcreate") {
            $order = "createtime desc";
        } elseif ($orderby == "newupdate") {
            $order = "updatetime desc";
        } elseif ($orderby == "hot") {
            $order = "view desc";
        } elseif ($orderby == "jing") {
            $order = "is_hot desc";
        } else {
            $order = "is_hot desc,view desc";
        }
        $list = CircleList::where($where)->page($page, $page_size)->field("id,uid,createtime,content,cir_id,pics,view,extend,video")->order($order)->select();
        $total = CircleList::where($where)->count();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                //处理是否已经关注我 是显示互相关注，显示粉丝头像昵称
                $list[$key]['user'] = $this->_suer_info($value['uid']);
                $list[$key]['cir_name'] = $this->_cir_name($value['cir_id']);
                $list[$key]['createtime'] = $this->timeTran($value['createtime']);
                //统计评论数
                $list[$key]['comment_count'] = $this->getCountComment($value['id'], '1');
                //统计点赞数
                $list[$key]['love_count'] = $this->getCountLove($value['id'], '1');
                $list[$key]['has_zan'] = $this->hasLove($uid, $value['id'], '1');
                $list[$key]['pics'] = $this->get_imgs($value['pics']);
                $list[$key]['video'] = $this->get_img($value['video']);
                $list[$key]['pics_num'] = count($list[$key]['pics']);
                if($value['extend']){
                    $list[$key]['extend'] = json_decode(htmlspecialchars_decode($value['extend']),true);
                }else{
                    $list[$key]['extend'] = [];
                }
//                $list[$key]['extend'] =$this->get_extent_name($value['extend']);
            }
        }
        $data = array('data' => $list, 'total' => $total);
        if ($list) {
            $this->success(__('获取成功'), $data);
        } else {
            $this->success(__('未获取到数据'), []);
        }
    }


    /**
     * 圈子详情
     * @param  [type] $id       [description]
     * @param  [type] $uid       [description]
     * @return [type]            [description]
     */
    public function getCircleInfo($id, $uid, $returntype = "json")
    {
        if (empty($id) || empty($uid)) {
            $this->error(__('参数异常'));
        }
        $where['id'] = $id;
        $info = CircleList::where($where)->field("id,uid,createtime,content,cir_id,pics,view,weixin,status,extend,video")->find();
        if (empty($info['status'])) {
            $this->error(__('当前圈子已关闭'), []);
        }
        //处理是否已经关注我 是显示互相关注，显示粉丝头像昵称
        $info['user'] = $this->_suer_info($info['uid']);
        $info['createtime'] = $this->timeTran($info['createtime']);

        $info['cir_name'] = $this->_cir_name($info['cir_id']);
        //统计评论数
        $info['comment_count'] = $this->getCountComment($info['id'], '1');
        //统计点赞数
        $info['love_count'] = $this->getCountLove($info['id'], '1');
        $info['has_zan'] = $this->hasLove($uid, $info['id'], '1');
        $info['pics'] = $this->get_imgs($info['pics']);
        $info['video'] = $this->get_img($info['video']);
        $info['pics_num'] = count($info['pics']);
        if($info['extend']){
            $info['extend'] = json_decode(htmlspecialchars_decode($info['extend']),true);
        }else{
            $info['extend'] = [];
        }

//        $info['extend'] =$this->get_extent_name($info['extend']);

        if ($returntype == "data") {
            return $info;
        }
        if ($info) {
            CircleList::where($where)->setInc('view', 1);
            $this->success(__('获取成功'), $info);
        } else {
            $this->error(__('未获取到数据'), []);
        }
    }


    /**
     * 点赞操作
     * @param  [type] $uid  [description]
     * @param  [type] $type [description]
     * @param  [type] $pid  [description]
     * @return [type]       [description]
     */
    public function saveShoucang($uid, $type, $tid, $tuid)
    {
        if (empty($uid) || empty($type) || empty($tid) || empty($tuid)) {
            $this->error(__('参数异常'));
        }
        switch ($type) {
            case '1':
                $goodsinfo = CircleList::find($tid);
                if (empty($goodsinfo)) {
                    $this->error(__('未找到id为' . $tid . '的圈子，请检查参数。'));
                }
                break;
            case '2':
                $huodong = Comment::find($tid);
                if (empty($huodong)) {
                    $this->error(__('未找到id为' . $tid . '的评论，请检查参数。'));
                }
                break;
            case '3':
                $goodsinfo = CircleList::find($tid);
                if (empty($goodsinfo)) {
                    $this->error(__('未找到id为' . $tid . '的二手市场，请检查参数。'));
                }
                break;
            default:
                # code...
                break;
        }
        $Shoucang['type'] = $type;
        $Shoucang['tid'] = $tid;
        $Shoucang['tuid'] = $tuid;
        $Shoucang['uid'] = $uid;
        $has = Love::where($Shoucang)->find();
        if ($has) {
            $res = Love::where($Shoucang)->delete();
            $this->success(__('取消点赞成功'));
        } else {
            $Shoucang['createtime'] = time();
            $Shoucang['updatetime'] = time();
            $res = Love::insert($Shoucang);
            $this->success(__('点赞成功'));
        }
    }
    //获取类型扩展参数
    public function get_type_extend($cir_id){
        $one['cir_id'] = $cir_id;
        $one['status'] = 1;
        $list = CircleTypeExtend::where($one)->field('cir_id,title,type,code,status,values,index')->select();
        foreach (@$list as $key=>$item){
            if($item['values']){
                $list[$key]['values']=explode('|',$item['values']);
            }else{
                $list[$key]['values']=[];
            }
            if($item['type']=='date'){
                $list[$key]['index']=date('Y-m-d',time());
            }
        }
        $this->success(__('成功'), $list);
    }

    /**
     * 添加圈子
     * @param  [type] $cir_id       [description]
     * @param  [type] $xiao_id       [description]
     * @param  [type] $content       [description]
     * @param  [type] $pics       [description]
     * @param  [type] $is_sui       [description]
     * @param  [type] $weixin       [description]
     * @param  [type] $uid       [description]
     * @return [type]            [description]
     */
    public function AddCircle($cir_id, $xiao_id, $content, $pics, $is_sui, $weixin, $uid,$extend='',$video='')
    {
        if (empty($cir_id) || empty($uid) || empty($content)) {
            $this->error(__('缺少必填参数'));
        }
        $one['cir_id'] = $cir_id;
        $one['xiao_id'] = $xiao_id;
        $one['uid'] = $uid;
        $one['content'] = $content;
        $one['pics'] = $pics;
        $one['weixin'] = $weixin;
        $one['video'] = $video;

        $info = CircleList::where($one)->find();
        if ($info) {
            $this->error(__('已发布相同内容，请核对后再次发布'), []);
        }
        $one['extend'] = $extend;
        $one['is_sui'] = $is_sui;
        $one['status'] = 0; //状态是否直接发布
        $one['createtime'] = time();
        $one['updatetime'] = time();
        $res = CircleList::insert($one);
        if ($res) {
            $this->success(__('发布成功'), $res);
        } else {
            $this->error(__('发布失败'), []);
        }
    }

//    -------------------------------圈子  圈子相关接口 -end------------------------------------------


//    -------------------------------圈子  个人中心相关接口 -------------------------------------------

    /**
     * 获取用户显示信息
     * @param  [type] $uid       [description]
     * @return [type]            [description]
     */
    public function get_suer_info($uid, $myuid)
    {
        $info = $this->_suer_info($uid);
        $info['has_fen'] = $this->hasFen($myuid, $uid);
        $info['love_count'] = $this->_circle_love_count(['tid' => $uid]);
        $info['fen_count'] = $this->_circle_fen_count(['tid' => $uid]);
        $info['guan_count'] = $this->_circle_fen_count(['uid' => $uid]);
        $this->success(__('成功'), $info);
    }


    /**
     * 关注用户操作
     * @param  [type] $uid  [description]
     * @param  [type] $type [description]
     * @param  [type] $pid  [description]
     * @return [type]       [description]
     */
    public function saveFen($uid, $tid)
    {
        if (empty($uid) || empty($tid)) {
            $this->error(__('参数异常'));
        }
        if ($uid == $tid) {
            $this->error(__('不能关注自己'));
        }
        $user = \app\common\model\User::getById($tid);
        $menber = \app\common\model\User::find($tid);
        if (empty($menber)) {
            $this->error(__('被关注用户id不对，请检查参数'));
        }
        $fen['tid'] = $tid;
        $fen['uid'] = $uid;
        $has = Fen::where($fen)->find();
        if ($has) {
            $res = Fen::where($fen)->delete();
            $this->success(__('取消关注成功'), $res);
        } else {
            $fen['createtime'] = time();
            $res = Fen::insert($fen);
            $this->success(__('关注成功'), $res);
        }
    }

    /**
     * 用户动态列表
     * @param  [type] $uid       [description]
     * @param  [type] $myuid     [description]
     * @param  [type] $page      [description]
     * @return [type]            [description]
     */
    public function getUserCirclelist($uid, $myuid, $page = 1)
    {
        if (empty($uid) || empty($myuid)) {
            $this->error(__('参数异常'));
        }
        $page = $page ? $page : 1;    //当前分页
        $page_size = $this->request->post("page_size") ?? 10;    //当前分页
        $where['uid'] = $uid;
        $order = "createtime desc";
        $list = CircleList::where($where)->page($page, $page_size)->field("id,uid,createtime,content,cir_id,pics,video,view,extend")->order($order)->select();
        $total = CircleList::where($where)->count();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                //处理是否已经关注我 是显示互相关注，显示粉丝头像昵称
//                $list[$key]['user'] = $this->_suer_info($value['uid']);
                $list[$key]['createtime'] = $this->timeTran($value['createtime']);
                $list[$key]['cir_name'] = $this->_cir_name($value['cir_id']);
                //统计评论数
                $list[$key]['comment_count'] = $this->getCountComment($value['id'], '1');
                //统计点赞数
                $list[$key]['love_count'] = $this->getCountLove($value['id'], '1');
                $list[$key]['has_zan'] = $this->hasLove($myuid, $value['id'], '1');
                $list[$key]['pics'] = $this->get_imgs($value['pics']);
                $list[$key]['video'] = $this->get_img($value['video']);
                $list[$key]['pics_num'] = count($list[$key]['pics']);
                if($value['extend']){
                    $list[$key]['extend'] = json_decode(htmlspecialchars_decode($value['extend']),true);
                }else{
                    $list[$key]['extend'] = [];
                }
//                $list[$key]['extend'] =$this->get_extent_name($value['extend']);
            }
        }
        $data = array('data' => $list, 'total' => $total);
        if ($list) {
            $this->success(__('获取成功'), $data);
        } else {
            $this->success(__('未获取到数据'), []);
        }
    }
//[{"组局人数":"10"},{"组局地点":"北京市朝阳区1号"},{"每人费用":"200"},{"截止日期":"2023-12-22"},{"组局类型":"2"},{"组局形式":"2"}]

    //获取扩展参数的数据  -- 已废弃
    public function get_extent_name($extend){
        if(empty($extend)) return [];
        $extend = json_decode(htmlspecialchars_decode($extend),true);
        $TypeextendModel = new \app\admin\model\circle\CircleTypeExtend();
        $Typeextendarr = $TypeextendModel->where('values','<>','')->column('values', 'title');
        foreach ($extend as $key=>$item){
            foreach ($item as $k=>$i) {
                if(in_array($k,['付款方式','装修','组局类型','组局形式'])){
                    $arr = explode('|',$Typeextendarr[$k]);
                    $extend[$key][$k]= $arr[$i];
                }
            }
        }
        return $extend;
    }



//    -------------------------------圈子  个人中心相关接口 -end------------------------------------------


//    -------------------------------圈子  评论相关接口  ------------------------------------------

    /**
     * 发表评论   未完成
     * @param  [type] $fid      [description]
     * @param  [type] $xiao_id       [description]
     * @param  [type] $content       [description]
     * @param  [type] $pics       [description]
     * @param  [type] $is_sui       [description]
     * @param  [type] $weixin       [description]
     * @param  [type] $uid       [description]
     * @return [type]            [description]
     */
    public function AddComment($fid, $tid, $info, $uid)
    {
        if (empty($tid) || empty($uid) || empty($info)) {
            $this->error(__('缺少必填参数'));
        }
        $one['fid'] = $fid;
        $one['tid'] = $tid;
        $one['uid'] = $uid;
        $one['info'] = $info;
        $info = Comment::where($one)->find();
        if ($info) {
            $this->error(__('已发布相同评论，请核对后再次发布'), []);
        }
        $one['createtime'] = time();
        $one['updatetime'] = time();
        $one['status'] = 0; //状态是否直接发布
        $res = Comment::insert($one);
        if ($res) {
            $this->success(__('发布成功评论'), $res);
        } else {
            $this->error(__('发布评论失败'), []);
        }
    }

    /**
     * 获取圈子评论-分页评论
     * @param  [type] $uid      [description]
     * @param  [type] $fidid [description]
     * @param  [type] $type     [description]
     * @return [type]           [description]
     */
    public function getCommentPage($uid, $fid, $tid, $page, $page_size = 10)
    {
        if (empty($uid) || empty($tid)) {
            $this->error(__('参数异常'));
        }
        $page = $page ? $page : 1;    //当前分页
        $page_size = $page_size ? $page_size : 10;    //当前分页
        $where['status'] = 1;
        $where['fid'] = $fid;
        $where['tid'] = $tid;
        $list = Comment::where($where)->page($page, $page_size)->select();
        $total = Comment::where($where)->count();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                $list[$key]['createtime'] = $this->timeTran($value['createtime']);
                //处理是否已经关注我 是显示互相关注，显示粉丝头像昵称
                $list[$key]['user'] = $this->_suer_info($value['uid']);
                $list[$key]['has_zan'] = $this->hasLove($uid, $value['id'], '2'); //是否点赞评论
                $childlist = [];
                if ($value['fid'] == 0) {
                    $childlist = Comment::where(['fid' => $value['id']])->limit(5)->select();
                    foreach ($childlist as $k => $v) {
                        $childlist[$k]['user'] = $this->_suer_info($v['uid']);
                        $childlist[$k]['createtime'] = $this->timeTran($value['createtime']);
                    }
                    $list[$key]['childlist'] = $childlist;
                }
            }
        }
        $data = array('data' => $list, 'total' => $total);
        if ($list) {
            $this->success(__('获取成功'), $data);
        } else {
            $this->success(__('未获取到数据'), []);
        }
    }


//    -------------------------------圈子  评论相关接口 -end------------------------------------------


//    -------------------------------消息  各项动态列表------------------------------------------


    /**
     * 我的点赞 点赞列表  未完成
     * @param  [type] $uid       [description]
     * @param  [type] $page      [description]
     * @param  [type] $page_size [description]
     * @return [type]            [description]
     */
    public function getLovelist($uid, $page, $page_size)
    {
        if (empty($uid)) {
            $this->error(__('参数异常'));
        }
        $page = $page ? $page : 1;    //当前分页
        $page_size = $page_size ? $page_size : 10;    //当前分页
        $list = Love::where(['uid' => $uid])->page($page, $page_size)->field('createtime,uid,tid,tuid,type,id')->select();
        $total = Love::where(['uid' => $uid])->count();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                if ($value['type'] == 1) {
                    $list[$key]['info'] = $this->getCircleInfo($value['tid'], $uid, "data");
                } elseif ($value['type'] == 2) {
                    $fidinfo = Comment::where(['id' => $value['tid']])->field('id,info,createtime,uid,tid')->find();
                    $fidinfo['user'] = $this->_suer_info($fidinfo['uid']);
                    $fidinfo['createtime'] = $this->timeTran($fidinfo['createtime']);
                    $fidinfo['has_zan'] = 1;
                    if ($fidinfo['tid']) {
                        $list[$key]['info'] = $this->getCircleInfo($fidinfo['tid'], $uid, "data");
                    }
                    $list[$key]['commentinfo'] = $fidinfo;
                }
                $list[$key]['createtime'] = $this->timeTran($value['createtime']);
            }
        }
        $data = array('data' => $list, 'total' => $total);
        if ($list) {
            $this->success(__('获取成功'), $data);
        } else {
            $this->success(__('未获取到数据'), []);
        }
    }

    /**
     * 我的评论 评论列表    未完成
     * @param  [type] $uid       [description]
     * @param  [type] $page      [description]
     * @param  [type] $page_size [description]
     * @return [type]            [description]
     */
    public function getCommentlist($uid, $page, $page_size)
    {
        if (empty($uid)) {
            $this->error(__('参数异常'));
        }
        $page = $page ? $page : 1;    //当前分页
        $page_size = $page_size ? $page_size : 10;    //当前分页
        $where['uid'] = $uid;
        $where['status'] = 1;
        $list = Comment::where($where)->page($page, $page_size)->select();
        $total = Comment::where($where)->count();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                if ($value['fid']) {
                    $fidinfo = Comment::where(['id' => $value['fid']])->field('id,info,createtime,uid,tid')->find();
                    $fidinfo['user'] = $this->_suer_info($fidinfo['uid']);
                    $fidinfo['createtime'] = $this->timeTran($fidinfo['createtime']);
                    if ($fidinfo['tid']) {
                        $fidinfo['tidinfo'] = CircleList::where(['id' => $fidinfo['tid']])->field('id,content,pics')->find();
                    }
                    $list[$key]['fidinfo'] = $fidinfo;
                }
                if ($value['tid']) {
                    $list[$key]['tidinfo'] = $this->get_cir_info($value['tid']);
//                    $list[$key]['tidinfo']['has_zan'] = $this->hasLove($uid, $value['tid'], '1');
                }
                $list[$key]['user'] = $this->_suer_info($value['uid']);
                $list[$key]['createtime'] = $this->timeTran($value['createtime']);
            }
        }
        $data = array('data' => $list, 'total' => $total);
        if ($list) {
            $this->success(__('获取成功'), $data);
        } else {
            $this->success(__('未获取到数据'), []);
        }
    }
    // 圈子内容缓存
    public function get_cir_info($id){

        $data = Cache::get("circle_list_info_".$id);
        if($data){
            return $data;
        }

        $tidinfo = CircleList::where(['id' => $id])->field('id,content,pics,uid,cir_id,createtime')->find();
        $tidinfo['pics'] = $this->get_imgs($tidinfo['pics']);
        $tidinfo['pics_num'] = count($tidinfo['pics']);
        //处理是否已经关注我 是显示互相关注，显示粉丝头像昵称
        $tidinfo['user'] = $this->_suer_info($tidinfo['uid']);
        $tidinfo['cir_name'] = $this->_cir_name($tidinfo['cir_id']);
        $tidinfo['createtime'] = $this->timeTran($tidinfo['createtime']);
        //统计评论数
        $tidinfo['comment_count'] = $this->getCountComment($tidinfo['id'], '1');
        //统计点赞数
        $tidinfo['love_count'] = $this->getCountLove($tidinfo['id'], '1');
        Cache::set("circle_list_info_".$id, $tidinfo,60*60*24*30);
        return $tidinfo;
    }

    /**
     * 我的粉丝  粉丝列表
     * @param  [type] $uid       [description]
     * @param  [type] $page      [description]
     * @param  [type] $page_size [description]
     * @return [type]            [description]
     */
    public function getFenlist($uid, $page, $page_size)
    {
        if (empty($uid)) {
            $this->error(__('参数异常'));
        }
        $page = $page ? $page : 1;    //当前分页
        $page_size = $page_size ? $page_size : 10;    //当前分页
        $fen = Fen::where(['tid' => $uid])->page($page, $page_size)->field("uid")->select();
        $total = Fen::where(['tid' => $uid])->count();
        if (!empty($fen)) {
            foreach ($fen as $key => $value) {
                //处理是否已经关注我 是显示互相关注，显示粉丝头像昵称
                $fen[$key]['user'] = $this->_suer_info($value['uid']);
                $fen[$key]['has_fen'] = $this->hasFen($uid, $value['uid']);
                $fen[$key]['quan_num'] = $this->_circle_count(['uid'=>$value['uid']]);
            }
        }
        $data = array('data' => $fen, 'total' => $total);
        if ($fen) {
            $this->success(__('获取成功'), $data);
        } else {
            $this->success(__('未获取到数据'), []);
        }
    }


    /**
     * 我的关注  关注用户列表
     * @param  [type] $uid       [description]
     * @param  [type] $page      [description]
     * @param  [type] $page_size [description]
     * @return [type]            [description]
     */
    public function getGuanlist($uid, $page, $page_size)
    {
        if (empty($uid)) {
            $this->error(__('参数异常'));
        }
        $page = $page ? $page : 1;    //当前分页
        $page_size = $page_size ? $page_size : 10;    //当前分页
        $fen = Fen::where(['uid' => $uid])->page($page, $page_size)->field("tid")->select();
        $total = Fen::where(['uid' => $uid])->count();
        if (!empty($fen)) {
            foreach ($fen as $key => $value) {
                //处理是否已经关注我 是显示互相关注，显示粉丝头像昵称
                $fen[$key]['user'] = $this->_suer_info($value['tid']);
                $fen[$key]['has_fen'] = 1;
                $fen[$key]['quan_num'] = $this->_circle_count(['uid'=>$value['tid']]);
            }
        }
        $data = array('data' => $fen, 'total' => $total);
        if ($fen) {
            $this->success(__('获取成功'), $data);
        } else {
            $this->success(__('未获取到数据'), []);
        }
    }

//    -------------------------------消息  各项动态列表------------------------------------------


//    -------------------------------圈子  辅助调用相关接口 -------------------------------------------

    /**
     * 获取用户显示信息
     * @param  [type] $uid       [description]
     * @return [type]            [description]
     */
    public function _suer_info($uid)
    {
        $info = \app\common\model\User::field('id,avatar,nickname,gender,bio')->find($uid);
        $info['avatar'] = $this->get_img($info['avatar']);
        return $info;
    }

    /**
     * 获取圈子显示信息
     * @param  [type] $uid       [description]
     * @return [type]            [description]
     */
    public function _cir_name($id)
    {
        $info = Type::where(['id' => $id])->value('name');
        return $info;
    }


    public function _circle_count($where)
    {
        return CircleList::where($where)->count();
    }

    public function _circle_user_count($where)
    {
        return Db::name('circle_user')->where($where)->count();
    }

    public function _circle_fen_count($where)
    {
        return Fen::where($where)->count();
    }

    public function _circle_love_count($where)
    {
        return Love::where($where)->count();
    }


    /**
     * 统计评论数
     * @param  [type] $pid  [description]
     * @param  [type] $type [description]
     * @return [type]       [description]
     */
    function getCountComment($tid, $type = '')
    {
        $count = Comment::where(['type' => $type, 'tid' => $tid])->count();
        return $count;
    }

    /**
     * 统计点赞数
     * @param  [type] $tid  [description]
     * @param  [type] $type [description]
     * @return [type]       [description]
     */
    function getCountLove($tid, $type)
    {
        $count = Love::where(['type' => $type, 'tid' => $tid])->count();
        return $count;
    }

    //是否已点赞
    function hasLove($uid, $tid, $type)
    {
        $count = Love::where(['uid' => $uid, 'type' => $type, 'tid' => $tid])->count();
        return $count;
    }

    //是否已关注用户
    function hasFen($uid, $tid)
    {
        $count = Fen::where(['uid' => $uid, 'tid' => $tid])->count();
        return $count;
    }

    /**
     * 计算几秒前，几分前，几小时前，几天前
     * $the_time    时间戳
     * $format      时间显示格式
     */
    function timeTran($the_time, $format = null)
    {
        $now_time = date("Y-m-d H:i:s", time());
        $now_time = strtotime($now_time);
        $show_time = $the_time;
        $dur = $now_time - $show_time;
        if (empty($format)) $format = 'Y-m-d H:i:s';
        if ($dur < 0) {
            return date($format, $the_time);
        } else {
            if ($dur < 60) {
                return $dur . '秒前';
            } else {
                if ($dur < 3600) {
                    return floor($dur / 60) . '分钟前';
                } else {
                    if ($dur < 86400) {
                        return floor($dur / 3600) . '小时前';
                    } else {
                        if ($dur < 259200) {//3天内
                            return floor($dur / 86400) . '天前';
                        } else {
                            return date($format, $the_time);
                        }
                    }
                }
            }
        }
    }

    public function get_imgs($url)
    {
        if(empty($url)) return [];
        if(strpos($url, ',') !== false){
            $arr = explode(",",$url);
            foreach ($arr as $item){
                $res[] =  $this->get_img($item);
            }
        }elseif($url){
            $res[] =  $this->get_img($url);
        }
        return  $res;
    }

    /**
     * 上传文件  多图片文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        $attachment = null;
        //默认普通上传文件
        $files = $this->request->file('file');
        try {
            $upload = new Upload($files);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }
        $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, "https://www.manchengsh.com")]);
    }

    /**
     * 上传文件  多图片文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function uploads()
    {
        $attachment = null;
        //默认普通上传文件
        $files = $this->request->file('files');
        foreach ($files as $image) {
            try {
                $upload = new Upload($image);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }
            $res[] = cdnurl($attachment->url);
        }
        $this->success(__('Uploaded successful'), $res);
    }


    /**
     * 上传文件  多图片文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function video()
    {
        $attachment = null;
        //默认普通上传文件
        $files = $this->request->file('video');
        $upload = new Upload($files);
        $attachment = $upload->upload();
//        var_dump($attachment);die();
        $res = cdnurl($attachment->url);
        $this->success(__('Uploaded successful'), $res);
//
//        $getID3 = new getID3;
//        $path = env('root_path') . "public/";
//
//        // 音频文件
//        $audioFile = $path . "Kalimba.mp3";
//        // 视频文件
//        $videoFile = $path . "Wildlife.wmv";
//
//        // 分析文件
//        $audioFileInfo = $getID3->analyze($audioFile);
//        $videoFileInfo = $getID3->analyze($videoFile);
//
//        // 测试获取视频，音频时长信息
//        // 获取秒数
//        $audioSecond = $audioFileInfo['playtime_seconds'];
//        // 获取格式化时长
//        $audioFormat = $audioFileInfo['playtime_string'];
//
//        dump($audioSecond);
//        dump(gmdate("H:i:s", $audioSecond));
//        dump($audioFormat);


    }


    public function get_img($url)
    {
        if(empty($url)) return "";
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        $parsed_url = parse_url($url);
        if (isset($parsed_url['host'])) {
            // 如果图片地址中包含域名，则直接返回
            $res= $url;
        } else {
            $domain = $protocol."://".$_SERVER['SERVER_NAME'];
            $cdnurl = \think\Config::get('upload.cdnurl');
//            $domain = "https://img.manchengsh.com";
            $domain = "https://www.manchengsh.com";
            // 否则补全域名后返回
            $res= $domain . $url;
            $res = cdnurl($res);
        }
//        $res = str_replace('www.manchengsh.com','img.manchengsh.com',$res);
        return $res;
    }

}
